package com.weirn.spring.commons.utils;

import com.alibaba.fastjson.JSONObject;
import com.weirn.spring.commons.constants.AppIdEnum;
import com.weirn.spring.commons.vo.ConfigVO;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.dom4j.*;
import org.springframework.util.StringUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * Created by runing.wei on 2018/6/27.
 */
public class MakeExcelTest {

    private static final Long maxSize = 32767L;

    private static String path = "/Users/yp-tc-2563/Downloads/_apps_data_tomcat-temp_20180612185510.xml";

    // 产生要储存的集合
    protected static List<ConfigVO> getUsers() {
        List<ConfigVO> lists = null;
        try {
            lists = Dom4jUtils.readXMLDemo ( path );
        } catch ( Exception e ) {
            e.printStackTrace ();
        }
        return lists;
    }



    public static void test() {
        //第一步，创建一个workbook对应一个excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        //第二部，在workbook中创建一个sheet对应excel中的sheet
        HSSFSheet sheet = workbook.createSheet("用户表一");
        //第三部，在sheet表中添加表头第0行，老版本的poi对sheet的行列有限制
        HSSFRow row = sheet.createRow(0);
        //第四步，创建单元格，设置表头
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("命名空间namespace");
        cell = row.createCell(1);
        cell.setCellValue("配置类型type");
        cell = row.createCell(2);
        cell.setCellValue("所属应用appId");
        cell = row.createCell(3);
        cell.setCellValue("配置键configKey");
        cell = row.createCell(4);
        cell.setCellValue("值类型valueTypeStr");
        cell = row.createCell(5);
        cell.setCellValue("值数据类型valueDataTypeStr");
        cell = row.createCell(6);
        cell.setCellValue("值value");
        cell = row.createCell(7);
        cell.setCellValue("描述description");

        //第五步，写入实体数据，实际应用中这些数据从数据库得到,对象封装数据，集合包对象。对象的属性值对应表的每行的值
        List<ConfigVO> configVOS = getUsers();
        int count = 1;
        for (int i = 0; i < configVOS.size(); i++) {

            ConfigVO configVO = configVOS.get(i);
            if(configVO.getAppId () == AppIdEnum.TZT.getId ()
                    || configVO.getAppId () == AppIdEnum.JRCONFIG.getId ()
                    || configVO.getConfigKey ().contains ( "TZT" )
                    || configVO.getConfigKey ().contains ( "NEWTZT" )){
                System.out.println ( JSONObject.toJSONString ( configVO ));
                //创建单元格设值
                HSSFRow row1 = sheet.createRow(count);
                row1.createCell(0).setCellValue(configVO.getNamespace ());
                row1.createCell(1).setCellValue(configVO.getType ());
                row1.createCell(2).setCellValue(AppIdEnum.valueOf ( configVO.getAppId () ));
                row1.createCell(3).setCellValue(getValue(configVO.getConfigKey ()));
                row1.createCell(4).setCellValue(getValue(configVO.getValueTypeStr ()));
                row1.createCell(5).setCellValue(getValue(configVO.getValueDataTypeStr ()));
                String valueString = null;
                if("VALUE".equals ( configVO.getValueTypeStr () )){
                    valueString = configVO.getValue ();
                }else{
                    Document document = null;
                    try {
                        document = DocumentHelper.parseText(configVO.getValue ()); // 将字符串转为XML
                    } catch ( DocumentException e ) {
                        e.printStackTrace ();
                    }
                    Element node = document.getRootElement();
                                        if("MAP".equals ( configVO.getValueTypeStr () )){
                        Map<String,String> mapString = new HashMap<String,String> (  );
                        valueString = getMapFromXml("MAP",node,mapString);
                    }else if("LIST".equals ( configVO.getValueTypeStr () )){
                        List<String> listString = new LinkedList<String> (  );
                        valueString = getListFromXml("LIST",node,listString);
                    }else {
                        valueString = configVO.getValue ();
                    }
                }

                System.out.println ("配置值:"+valueString);
                row1.createCell(6).setCellValue(valueString);
                row1.createCell(7).setCellValue(getValue(configVO.getDescription ()));

                count++;
            }

        }

        //将文件保存到指定的位置
        try {
            FileOutputStream fos = new FileOutputStream("/Users/yp-tc-2563/Downloads/configVo.xls");
            workbook.write(fos);
            System.out.println("写入成功");
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args){

        test();
//        String value = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <config-value><value key=\"10000447970\">tztbk</value></config-value>";
//        // 通过read方法读取一个文件 转换成Document对象
//        Document document = null;
//        try {
//            document = DocumentHelper.parseText(value); // 将字符串转为XML
//        } catch ( DocumentException e ) {
//            e.printStackTrace ();
//        }
//        Element node = document.getRootElement();
//        Map<String,String> mapString = new HashMap<String,String> (  );
//        String valueString = getMapFromXml("MAP",node,mapString);
//        System.out.println ("解析结果为"+valueString);
    }

    private static String getListFromXml(String valueTypeStr,Element node,List listString){

        Iterator<Element> it = node.elementIterator();

        if(node.getName ().equals ( "value" )){

            if("MAP".equals ( valueTypeStr )){
                System.out.println ("参数异常");
            }else if("LIST".equals ( valueTypeStr )){
                String value = node.getText ();
                System.out.println ("list:"+value);
                listString.add ( value );
            }else{
                System.out.println ("参数异常");
                return node.getText ();
            }
        }else{
            while(it.hasNext ()){
                getListFromXml ( valueTypeStr,it.next (),listString );
            }
        }

        return JSONObject.toJSONString ( listString );

    }

    private static String getMapFromXml(String valueTypeStr,Element node,Map<String,String> mapString){
        List<Attribute> list = node.attributes();

        Iterator<Element> it = node.elementIterator();

        if(node.getName ().equals ( "value" )){

            if("MAP".equals ( valueTypeStr )){
                String key = node.attributeValue ( "key" );
                String value = node.getText ();
                System.out.println ("key:"+key + ",Value:"+value);
                mapString.put ( key,value );
            }else if("LIST".equals ( valueTypeStr )){
                String value = node.getText ();
                System.out.println ("list:"+value);
                System.out.println ("参数异常");
            }else{
                return node.getText ();
            }
        }else{
            while(it.hasNext ()){
                getMapFromXml ( valueTypeStr,it.next (),mapString );
            }
        }

        return JSONObject.toJSONString ( mapString );
    }

    private static String getValueFromXml(String valueTypeStr,String valueDataTypeStr,Element node){

        List<Attribute> list = node.attributes();
//         遍历属性节点
        for (Attribute attr : list) {
            System.out.println(attr.getText() + "-----" + attr.getName()
                    + "---" + attr.getValue());
        }

        if (!(node.getTextTrim().equals(""))) {
            System.out.println("文本内容：：：：" + node.getText());
        }

        Iterator<Element> it = node.elementIterator();

        if(node.getName ().equals ( "value" )){

            if("MAP".equals ( valueTypeStr )){
                String key = node.attributeValue ( "key" );
                String value = node.getText ();
                System.out.println ("key:"+key + ",Value:"+value);
            }else if("LIST".equals ( valueTypeStr )){
                String value = node.getText ();
                System.out.println ("list:"+value);
            }else{
                return node.getText ();
            }
        }else{
            while(it.hasNext ()){
                getValueFromXml ( valueTypeStr,null,it.next () );
            }
        }

        return null;
    }

    private static String getValue(String valueTypeStr,String valueDataTypeStr,String value){

        if("VALUE".equals ( valueTypeStr )){
            return value;
        }
        // 通过read方法读取一个文件 转换成Document对象
        Document document = null;
        try {
            document = DocumentHelper.parseText(value); // 将字符串转为XML
        } catch ( DocumentException e ) {
            e.printStackTrace ();
        }
        Element node = document.getRootElement();
        List<Attribute> list = node.attributes();
//         遍历属性节点
        for (Attribute attr : list) {
            System.out.println(attr.getText() + "-----" + attr.getName()
                    + "---" + attr.getValue());
        }

        if (!(node.getTextTrim().equals(""))) {
            System.out.println("文本内容：：：：" + node.getText());
        }

        Iterator<Element> it = node.elementIterator();

        if(node.getName ().equals ( "value" )){

            if("MAP".equals ( valueTypeStr )){
                Map<String,String> valueMap = new HashMap<String,String> (  );

//                List<Attribute> list = node.attributes();

            }else if("LIST".equals ( valueTypeStr )){

            }else{
                return value;
            }
        }else{
            getValue ( null,null,it.next ().asXML () );
        }

        return null;
    }


    private static String getValue(String value){

        if( StringUtils.isEmpty ( value )){
            return value;
        }
        if(value.length () >  maxSize){
            return value.substring ( 0, Math.toIntExact ( maxSize ) );
        }
        return value;
    }
}
